package com.example.mobileshop;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import com.example.mobileshop.controller.UserController;
import com.example.mobileshop.models.User;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginFragment extends Fragment{
	private LoginFragment(){}
	
	private static LoginFragment instance = new LoginFragment();
	
	public static LoginFragment instance(){
		return instance; 
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_login, container, false);   
        final TextView registerScreen = (TextView) rootView.findViewById(R.id.link_to_register);
        final Button btnLogin = (Button) rootView.findViewById(R.id.btnLogin);
        final EditText txtEmail = (EditText) rootView.findViewById(R.id.login_email);
        final EditText txtPassword = (EditText) rootView.findViewById(R.id.login_password);
        getActivity().getActionBar().setTitle(R.string.SignIn_screen);
        
        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                // Switching to Register screen
            	Fragment fragment = RegisterFragment.instance();             	
    			FragmentManager fragmentManager = getFragmentManager();
    			fragmentManager.beginTransaction()
    					.replace(R.id.frame_container, fragment).commit();        			        		
            }
        });
        
        btnLogin.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String email = txtEmail.getText().toString();
				String password = txtPassword.getText().toString();				
				User user = new User();
				user.setEmail(email);
				user.setEmail(password);
				new Login().execute(user);
			}
		});
        return rootView;        
    }	
	
	/**
     * Async task class to get json by making HTTP call
     * */
    private class Login extends AsyncTask<User, Void, Void> {    	    	    	     	    	
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();             
        }

		@Override
		protected Void doInBackground(User... arg0) {
			try {
				UserController userController = new UserController();
				HttpResponse response = userController.authenticateUser(arg0[0]);
				if(response != null && response.getStatusLine().getStatusCode() == 200){
					// Switching to shops fragment					 					
					String responseData = EntityUtils.toString(response.getEntity(), "utf-8");					
	            	Fragment fragment = ShopsFragment.instance();             	
	            	Bundle args = new Bundle();
	                args.putString(ShopsFragment.BUNDLE_KEY_LOGIN, responseData);
	                args.putString(ShopsFragment.BUNDLE_KEY_PRE_FRAGMENT, getActivity().getTitle().toString());
	                fragment.setArguments(args);	                
	    			FragmentManager fragmentManager = getFragmentManager();    			
	    			fragmentManager.beginTransaction()
	    					.replace(R.id.frame_container, fragment).commit();			
				}else{
					
				}
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);                   
        }    	
    }
}